<template>
  <div>
    <el-button @click="creadBtn">创建时间轴</el-button>
    <div class="slide-ruler">
      <div v-for="time of timeList" :key="time" class="scale">{{ time }}</div>
    </div>
    <draggable
      v-model="rows"
      class="row sortable-list"
      animation="300"
      handle=".mover"
      @end="end"
    >

      <!--  v-show="row.items.length !==0" -->

      <div
        v-for="(row,index) in rows"
        :key="row.index"
        class="sortable"
        @click.stop="clickChoose(row) "
      >
        <span class="mover">+</span>
        <span>{{ index+1 }}</span>
        <div class="slide-list">
          <!--  @mousedown.stop="fatherMousedown($event, row.code, row)" -->
          <div
            :style=" row.disabled ? 'background:#C0C8D9;cursor:not-allowed;' : '' "
            class="slide-box"
          >
            <draggable
              :list="row.items"
              :group="{ name: 'row' }"
              class="row-item"
              handle=".mover"
              :move="onMove"
              @start="start"
              @end="end"
              @choose="choose"
              @add="add"
              @update="update"
              @unchoose="unchoose"
              @change="change"
              @input="input"
            >
              <!-- <i class="mover" style="background: #FFFFFF;">@@</i> -->
              <!-- <i class="mover" style="background: #FFFFFF;">{{ row.items.length }}</i> -->
              <div
                v-show="domObj.width != 0 && row.code == code"
                class="item"
                :style="`width: ${domObj.width}px; left: ${domObj.left}px; background: ${domObj.bg}`"
              />
              <!-- @mousedown.stop="itemMousedown($event, key, item, row.items)"  @click.stop="timeBlock(row.code, key, item)"-->
              <div
                v-for="(item, key) of row.items"
                :key="item.id"
                class="item"
                :style="`width: ${item.width}px; left: ${item.left}px; background: ${item.bg}`"
              >
                <i class="mover" style="background: #FFFFFF;">{{ key }}</i>
                <!-- <i v-show="item.changeTimeShow && iShow === key" class="i-left-class i-class" @mousedown.stop="checkI('left', $event, code, key, item, row.items)" />
                <i v-show="item.changeTimeShow && iShow === key" class="i-right-class i-class" @mousedown.stop="checkI('right', $event, code, key, item, row.items)" /> -->
              </div>
            </draggable>
          </div>
        </div>

      </div>
    </draggable>
    <div style="margin-top: 30px;">{{ rows }}</div>
  </div>
</template>
<script>
import draggable from 'vuedraggable'

export default {
  name: 'TwoLists',
  display: 'Two Lists',
  order: 1,
  components: {
    draggable
  },
  data() {
    return {
      enabled: true,
      disabled: false,
      rows: [],
      timeList: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
      // 声明的DOM对象
      domObj: {},
      // 左右i的显示
      iShow: null,
      typeVal: 1,
      // 是否是选中的时间子块
      loop: 0,
      // 存根数据
      stubData: {},
      // 每个子块的下拉框
      sonVal: null
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.domObj = {
        width: 0, // 宽度
        left: 0, // 左偏移量
        bg: '#637DEC', // 背景色（与背景值关联，对应着下拉框的值
        value: 1, // 背景值（与背景色关联，对应着下拉框的值
        startH: 0, // 开始时间（时
        startM: 0, // 开始时间（分
        endH: 0, // 结束时间（时
        endM: 0, // 结束时间（分
        changeTimeShow: false // 控制时间显示与时间调整
      }
      this.rows = [
        {
          index: 1,
          code: 0,
          copyShow: false,
          disabled: false,
          items: [
            { id: '001', 'width': 201, 'left': 382, 'value': 1, 'startH': 12, 'startM': 44, 'endH': 19, 'endM': 26, 'changeTimeShow': false, 'bg': '#637DEC' }
          ]
        },
        {
          index: 2,
          code: 1,
          items: [
            { id: '002', 'width': 102, 'left': 45, 'bg': '#637DEC', 'value': 1, 'startH': '01', 'startM': 30, 'endH': '04', 'endM': 54, 'changeTimeShow': false }
            // {
            //   id: '002',
            //   title: 'item 2'
            // },
            // {
            //   id: '003',
            //   title: 'item 3',
            //   width: 194,
            //   left: 167,
            //   bg: '#637DEC',
            //   value: 1,
            //   startH: '05',
            //   startM: 34,
            //   endH: 12,
            //   endM: '02',
            //   changeTimeShow: false
            // }
          ]
        },
        {
          index: 3,
          items: [
            // {
            //   id: '004',
            //   title: 'item 4',
            //   width: 133,
            //   left: 409,
            //   value: 1,
            //   startH: 13,
            //   startM: 38,
            //   endH: 18,
            //   endM: '04',
            //   changeTimeShow: false,
            //   bg: '#637DEC'
            // }
          ]
        }
      ]
    },
    // 下拉框选择
    onSelect(code) {
      this.domObj = {
        width: 0, // 宽度
        left: 0, // 左偏移量
        value: code, // 背景值（与背景色关联，对应着下拉框的值
        startH: 0, // 开始时间（时
        startM: 0, // 开始时间（分
        endH: 0, // 结束时间（时
        endM: 0, // 结束时间（分
        changeTimeShow: false
      }
      if (code === 1) {
        this.domObj.bg = '#637DEC'
      } else if (code === 2) {
        this.domObj.bg = '#74B557'
      } else if (code === 3) {
        this.domObj.bg = '#B83F42'
      } else if (code === 4) {
        this.domObj.bg = '#E58805'
      } else if (code === 5) {
        this.domObj.bg = '#B9E2FE'
      } else if (code === 6) {
        this.domObj.bg = '#AA6FFE'
      }
    },
    // 父节点的按下事件
    fatherMousedown(e, code, item) {
      console.log(e, code, item)
      // 控制是否还能创建
      if (item.items.length >= this.allNum || item.disabled) {
        return false
      }
      this.code = code
      // const op = e.target
      // 算出鼠标相对元素的位置
      const disX = e.clientX
      // console.log(e.clientX, op.offsetLeft, "相对位置是他left的值", disX);
      // left
      this.domObj.left = e.layerX
      // 开始时间
      this.domObj.startH = this.conversionhs('H', this.domObj.left * 2)
      this.domObj.startM = this.conversionhs('M', this.domObj.left * 2)
      // 鼠标移动事件
      document.onmousemove = (e) => {
        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        this.domObj.width = e.clientX - disX
        // 拖动的宽不能大于刻度，否则就等于 刻度-偏移的left = 最终宽
        if (this.domObj.width + this.domObj.left > 720) {
          this.domObj.width = 720 - this.domObj.left
        }
        // 结束时间
        this.domObj.endH = this.conversionhs('H', this.domObj.left * 2 + this.domObj.width * 2)
        this.domObj.endM = this.conversionhs('M', this.domObj.left * 2 + this.domObj.width * 2)
      }
      // 鼠标抬起事件
      document.onmouseup = (e) => {
        if (this.domObj.width > 0) {
          // console.log('width宽度==》》',this.domObj.width,'----left左偏移==》》',this.domObj.left)
          // console.log(`${this.domObj.startH} : ${this.domObj.startM} - ${this.domObj.endH} : ${this.domObj.endM}`)
          item.items.push(this.domObj)
        }
        this.onSelect(this.typeVal)
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    // 子块节点的长按
    itemMousedown(e, key, item, arr) {
      console.log(e, key, item, arr)
      this.loop = setTimeout(() => {
        this.loop = 0
        const disX = e.clientX
        const blockLeft = item.left// 左边偏移量left
        // const blockWidth = item.width// 子滑块的宽
        // 控制子块长按时的hover显示
        this.blockShow = false
        item.changeTimeShow = false
        // console.log('是否显示了按钮组',item.changeTimeShow)
        const arrCopy = JSON.parse(JSON.stringify(arr))
        // 对需要移动的子块的所在数组重新按照left大小排序
        function sortLeft(a, b) {
          return a.left - b.left
        }
        arrCopy.sort(sortLeft)
        // 处理左右滑动的范围
        let leftL = 0 // 往左滑动的范围
        let leftR = 720 // 往右滑动的范围
        let mark = 0
        for (let i = 0; i < arrCopy.length; i++) {
          if (arrCopy[i].left === item.left) {
            mark = i
            break
          }
        }
        if (arrCopy.length === 1) {
          leftL = 0 // 往左滑动的范围
          leftR = 720 // 往右滑动的范围
        } else {
          if (mark === 0) {
            leftL = 0 // 往左滑动的范围
            leftR = arrCopy[mark + 1].left // 往右滑动的范围
          } else if (mark === arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = 720
          } else if (mark !== 0 && mark < arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = arrCopy[mark + 1].left
          }
        }
        // console.log('arrCopy==',arrCopy,'==mark=',mark,'=leftL=',leftL,'=leftR=',leftR)
        // 子块鼠标移动事件
        document.onmousemove = (e) => {
          // console.log(e,'子块滑动事件',e.clientX,'--==--',e.clientX - disX,'---left=',blockLeft + (e.clientX - disX))
          if (blockLeft + (e.clientX - disX) <= leftL) {
            item.left = leftL
          } else if (item.width + (blockLeft + (e.clientX - disX)) <= leftR) {
            // console.log('总长==',item.width + blockLeft + (e.clientX - disX))
            item.left = blockLeft + (e.clientX - disX)
          }
          // 开始时间
          item.startH = this.conversionhs('H', item.left * 2)
          item.startM = this.conversionhs('M', item.left * 2)
          // 结束时间
          item.endH = this.conversionhs('H', item.left * 2 + item.width * 2)
          item.endM = this.conversionhs('M', item.left * 2 + item.width * 2)
        }
        // 子块鼠标抬起事件
        document.onmouseup = (e) => {
          this.blockShow = true
          this.iShow = null
          document.onmousemove = null
          document.onmouseup = null
        }
      }, 200)
      return false
    },
    // 子块节点的单击
    timeBlock(code, key, item) {
      console.log(code, key, item, item.value, this.loop, '@#$@@')
      clearTimeout(this.loop)
      if (this.loop === 0) {
        this.iShow = key
        this.sonVal = item.value
        // console.log('单击=',code, key, JSON.stringify(item) );
        this.stubData = JSON.parse(JSON.stringify(item))
        // 找到对应的节点，根据条件把对应节点打开或者关闭，但是其它节点要全部关闭
        this.rows.map((v, i) => {
          v.items.map((val, j) => {
            if (i === code && j === key) {
              item.changeTimeShow = !item.changeTimeShow
            } else {
              this.rows[i].items[j].changeTimeShow = false
            }
          })
        })
      }
      return false
    },
    // 选中的左右小方块
    checkI(type, e, code, key, item, arr) {
      this.loop = setTimeout(() => {
        this.loop = 0
        const disX = e.clientX
        const blockLeft = item.left// 左边偏移量left
        const blockWidth = item.width// 子滑块的宽
        // item.changeTimeShow = false
        item.value = this.stubData.value
        // console.log(item,'--->>>>>',this.stubData)
        // console.log('type==>>点击的那个',type, e, key, item, arr)
        const arrCopy = JSON.parse(JSON.stringify(arr))
        // 对需要移动的子块的所在数组重新按照left大小排序
        function sortLeft(a, b) {
          return a.left - b.left
        }
        arrCopy.sort(sortLeft)
        // 处理左右滑动的范围
        let leftL = 0 // 往左滑动的范围
        let leftR = 720 // 往右滑动的范围
        let mark = 0
        for (let i = 0; i < arrCopy.length; i++) {
          if (arrCopy[i].left === item.left) {
            mark = i
            break
          }
        }
        if (arrCopy.length === 1) {
          leftL = 0 // 往左滑动的范围
          leftR = 720 // 往右滑动的范围
        } else {
          if (mark === 0) {
            leftL = 0 // 往左滑动的范围
            leftR = arrCopy[mark + 1].left // 往右滑动的范围
          } else if (mark === arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = 720
          } else if (mark !== 0 && mark < arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = arrCopy[mark + 1].left
          }
        }
        // console.log('arrCopy==',arrCopy,'==mark=',mark,'=leftL=',leftL,'=leftR=',leftR)
        // 子块鼠标移动事件
        document.onmousemove = (e) => {
          // console.log(blockWidth,'子块滑动事件',e.clientX,'--==-运算的-',e.clientX - disX,'---left=',blockLeft + (e.clientX - disX))
          if (type === 'left') {
            if (blockLeft + (e.clientX - disX) < leftL) {
              item.left = leftL
            } else {
              if (blockWidth - (e.clientX - disX) >= 0) {
                item.left = blockLeft + (e.clientX - disX)
                item.width = blockWidth - (e.clientX - disX)
              }
            }
          } else if (type === 'right') {
            if (blockWidth + (blockLeft + (e.clientX - disX)) <= leftR) {
              item.width = blockWidth + (e.clientX - disX)
            }
          }
          // 开始时间
          item.startH = this.conversionhs('H', item.left * 2)
          item.startM = this.conversionhs('M', item.left * 2)
          // 结束时间
          item.endH = this.conversionhs('H', item.left * 2 + item.width * 2)
          item.endM = this.conversionhs('M', item.left * 2 + item.width * 2)
        }
        // 左右小方块的鼠标抬起事件
        document.onmouseup = (e) => {
          this.iShow = null
          if (item.width <= 0) {
            this.weekList[code].domArr.splice(key, 1)
          }
          document.onmousemove = null
          document.onmouseup = null
        }
      }, 200)
      return false
    },
    // 分钟 换算 时,分
    conversionhs(type, timeNum) {
      if (type === 'H') {
        return parseInt(timeNum / 60) < 10 ? '0' + parseInt(timeNum / 60) : parseInt(timeNum / 60)
      } else if (type === 'M') {
        return parseInt(timeNum % 60) < 10 ? '0' + parseInt(timeNum % 60) : parseInt(timeNum % 60)
      }
    },
    // 时，分 换算成 px
    conversionpx(type, pxNum) {
      if (type === 'left') {
        return (parseInt(pxNum.startH) * 60 + parseInt(pxNum.startM)) / 2
      } else if (type === 'width') {
        return ((parseInt(pxNum.endH) * 60 + parseInt(pxNum.endM)) - (parseInt(pxNum.startH) * 60 + parseInt(pxNum.startM))) / 2
      }
    },
    creadBtn() {
      // 找到数组中的最大index值
      const maxIndex = Math.max(...this.rows.map(row => row.index))
      // 创建新的行对象，增加一个新增的index
      const newRow = {
        index: maxIndex + 1,
        items: []
      }
      // 将新行对象添加到数组中
      this.rows.push(newRow)
    },
    start(e) {
      console.log(e, 'start')
    },
    end() {
      this.rows = this.rows.filter(row => row.items.length > 0)
      console.log(this.rows)
    },
    onMove(e, originalEvent) {
      console.log(e)
      console.log(originalEvent, 'originalEvent')
      // false表示阻止拖拽
      return true
    },
    choose() {
      // console.log(e, '鼠标点击选中要拖拽元素时的事件')
    },
    clickChoose(e) {
      console.log(e, '鼠标点击选中要拖拽元素')
    },
    add(e) {
      console.log(e, 'add')
    },
    update(e) {
      console.log(e, 'update')
    },
    unchoose(e) {
      console.log(e, 'unchoose')
    },
    sort(e) {
      console.log(e, 'sort')
    },
    // 被拖动的元素数据及被拖入后的下标
    change(e) {
      console.log(e, 'change')
      // this.dragNode = {
      //   data: event.added.element,
      //   newIndex: event.added.newIndex
      // }
    },
    // 拖入之后 draggable组件中的数据
    input(e) {
      console.log(e, 'input')
    },
    copyMouseenter(e) {
      console.log(e, 'eee')
    }
    // add: function() {
    //   this.list.push({ name: 'Juan' })
    // },
    // replace: function() {
    //   this.list = [{ name: 'Edgard' }]
    // },

  }
}
</script>
<style scoped lang="scss">
.sortable-list{
  height: 100%;
  background: grey;
  padding: 5px;
}
.row-item{
  display: flex;
  -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    box-flex: 1
}
.sortable{
  width: 810px;
  display: flex;
  align-items: end;
  background: red;
  margin-bottom: 8px;
  padding: 5px;
}

.row-v {
  // height: 50px;
  // width: 200px;
  background: rgba(0, 191, 255, 0.742);margin: 10px;

}
// 刻度
.slide-ruler {
  position: relative;
  left: -5px;
  width: 730px;
  display: flex;
  justify-content: space-between;
}
.scale {
  text-align: center;
  width: 15px;
  font-size: 12px;
}
.slide-list {
  width: 720px;
}
.slide-box {
  width: 100%;
  height: 20px;
  background: #000;
  display: flex;
  position: relative;
}
.item {
  height: 100%;
  position: absolute;
}
.i-class{
  width: 6px;
  height: 20px;
  position: absolute;
  display: inline-block;
  // background: url(../../../assets/image/xiaofk.png);
  background: greenyellow;
  background-position: -5px;
  z-index: 1;
}
.i-left-class{
  left: -3px;
}
.i-right-class{
  right: -3px;
}
.i-class:hover{
  cursor:w-resize
}
.timeHover {
  width: 100%;
  height: 100%;
  display: inline-block;
}

</style>
